# coding=utf-8
import uuid

from django.core.exceptions import ObjectDoesNotExist

from task.models import TaskBase, TaskExt, UserJoinTask
from people.models import User, UserPrivate
from common.config import *

from forms import *


class TaskTradeService(object):

    @classmethod
    def pay_task(cls, user_id, trade_num, trade_fare, pay_way):
        """
        :param pay_way: 支付方式
        :param user_id: 
        :param trade_num: 交易单号
        :param trade_fare: 交易金额 = 预算金额 + 押金
        :return: 
        """
        try:
            trade_task = TradeTask.objects.get(trade_num=trade_num)
            pay_form = PayTradeForm({
                'trade_num': trade_num,
                'fare': trade_fare,
                'pay_way': trade_pay_config[pay_way],
                'pay_user': user_id,
                'station': trade_config['paid'],
            }, instance=trade_task)
            if pay_form.is_valid():
                pay_form.save()

                # 更新用户的余额
                user_private = UserPrivate.objects.get(user_id=user_id)
                user_private.reduce_amount({'cash': float(trade_fare)})

                return {
                    'status': True,
                    'msg': '',
                }
            else:
                return {
                    'status': False,
                    'msg': pay_form.errors
                }
        except ObjectDoesNotExist:
            return {
                'status': False,
                'msg': 'trade_none',
            }

    @classmethod
    def calculate_task(cls, task_id, user_id):
        try:
            task_base = TaskBase.objects.get(pk=task_id)

            reward = task_base.task_value
            # 判断是否存在子任务
            if task_base.sub_task_num > 0:
                sub_tasks = TaskBase.objects.filter(task_id=task_id)
                # 计算全部的任务报酬
                for task in sub_tasks:
                    reward = reward + task.task_value
            task_amount = reward if reward > task_base.task_ext.fare_task else task_base.task_ext.fare_task
            task_amount = task_amount + task_base.task_ext.task_fare

            # 插入数据库，等待后续支付
            trade_from = TaskTradeForm({
                'pay_user': user_id,
                'task': task_id,
                'fare': task_amount,
                'trade_num': uuid.uuid1(),
                'pay_way': trade_pay_config['sys'],
                'station': trade_config['unpaid'],
            })
            if trade_from.is_valid():
                trade_from.save()

                return {
                    'status': True,
                    'msg': {
                        'total': task_amount,
                        'trade_num': trade_from.cleaned_data.get('trade_num'),
                    },
                }
            else:
                return {
                    'status': False,
                    'msg': trade_from.errors
                }
        except ObjectDoesNotExist:
            return {
                'status': False,
                'msg': 0,
            }

    @classmethod
    def grant(cls, task_id):
        try:
            task_base = TaskBase.objects.get(pk=task_id)
            if task_base.station is 6:
                return True

            task_base.station = 6
            task_base.save()

            task_joiners = UserJoinTask.objects.filter(task_base_id=task_id)
            for joiner in task_joiners:
                joiner.station = 6
                joiner.save()

                user_private = UserPrivate.objects.get(user_id=joiner.user_id)
                user_private.cash = user_private.cash + joiner.task_base.task_value
                user_private.save()
            return True
        except ObjectDoesNotExist as e:
            return False
